//
//  PPWebGrabProtocol.m
//  pickpic
//
//  Created by Jinxiao on 10/30/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPWebGrabProtocol.h"

@interface PPWebGrabProtocol ()
@property (readwrite, nonatomic, strong) NSURLConnection *connection;
@end

@implementation PPWebGrabProtocol

+ (NSHashTable *)observers
{
    static NSHashTable *observers;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        observers = [[NSHashTable alloc] initWithOptions:NSPointerFunctionsWeakMemory capacity:0];
    });
    return observers;
}

+ (void)registerObserver:(id <PPWebGrabProtocolDelegate>)observer {
    [self.observers addObject:observer];

    if(self.observers.count > 0) {
        [NSURLProtocol registerClass:[self class]];
    }
}

+ (void)unregisterObserver:(id <PPWebGrabProtocolDelegate>)observer {
    [self.observers removeObject:observer];

    if(self.observers.count == 0) {
        [NSURLProtocol unregisterClass:[self class]];
    }
}

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    if ([NSURLProtocol propertyForKey:@"PPWebGrabProtocol" inRequest:request]) {
        return NO;
    }
    return YES;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    return request;
}

- (void)startLoading {
    NSMutableURLRequest *newRequest = [self.request mutableCopy];
    newRequest.allHTTPHeaderFields = self.request.allHTTPHeaderFields;
    [NSURLProtocol setProperty:@YES forKey:@"PPWebGrabProtocol" inRequest:newRequest];

    _connection = [NSURLConnection connectionWithRequest:newRequest delegate:self];
}

- (void)stopLoading {
    [_connection cancel];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if ([response.MIMEType rangeOfString:@"image"].length) {
        for(id<PPWebGrabProtocolDelegate> observer in [self class].observers) {
            [observer protocol:self didRecognizedImageURL:connection.currentRequest.URL];
        }
    }

    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.client URLProtocol:self didLoadData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.client URLProtocolDidFinishLoading:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self.client URLProtocol:self didFailWithError:error];
}

@end
